package com.bdqn.ch02.JD.jd3;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * XMLAdd
 *
 * 使用DOM 进行对文档的添加
 * @aurhor Administrator  whs
 * @since 2024/7/1
 */
public class XMLAdd {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse("src/com/bdqn/ch02/JD/成绩信息.xml");

            Element studentEle = doc.createElement("student");
            studentEle.setAttribute("id","3");

            Element nameEle = doc.createElement("name");
            nameEle.setTextContent("帅帅");
            Element courseEle = doc.createElement("course");
            courseEle.setTextContent("100");
            Element scoreEle = doc.createElement("score");
            scoreEle.setTextContent("数学");

            studentEle.appendChild(nameEle);
            studentEle.appendChild(courseEle);
            studentEle.appendChild(scoreEle);
            Element ConEle = (Element) doc.getElementsByTagName("scores").item(0);
            ConEle.appendChild(studentEle);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transform = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);

            transform.setOutputProperty(OutputKeys.ENCODING, "gb2312");
            StreamResult result = new StreamResult(new FileOutputStream("src/com/bdqn/ch02/JD/成绩信息.xml"));

            transform.transform(domSource, result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

